from app import db
from datetime import datetime

class Sales(db.Model):
    __tablename__ = 'sales'
    
    id = db.Column(db.Integer, primary_key=True)
    car_id = db.Column(db.Integer, db.ForeignKey('cars.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)  # 销售人员ID
    customer_name = db.Column(db.String(100), nullable=False)
    customer_phone = db.Column(db.String(20))
    customer_address = db.Column(db.String(255))
    quantity = db.Column(db.Integer, default=1)
    unit_price = db.Column(db.Float, nullable=False)  # 销售单价
    total_price = db.Column(db.Float, nullable=False)  # 销售总价
    sale_date = db.Column(db.DateTime, default=datetime.utcnow)
    payment_method = db.Column(db.String(50))
    status = db.Column(db.String(20), default='completed')  # 销售状态：pending, completed, cancelled
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __init__(self, car_id, user_id, customer_name, unit_price, total_price, **kwargs):
        self.car_id = car_id
        self.user_id = user_id
        self.customer_name = customer_name
        self.unit_price = unit_price
        self.total_price = total_price
        self.customer_phone = kwargs.get('customer_phone')
        self.customer_address = kwargs.get('customer_address')
        self.quantity = kwargs.get('quantity', 1)
        self.sale_date = kwargs.get('sale_date', datetime.utcnow())
        self.payment_method = kwargs.get('payment_method')
        self.status = kwargs.get('status', 'completed')
        self.notes = kwargs.get('notes')
    
    def to_dict(self):
        return {
            'id': self.id,
            'car_id': self.car_id,
            'car_name': self.car.name if self.car else None,
            'user_id': self.user_id,
            'salesperson_name': self.salesperson.nickname if self.salesperson else None,
            'customer_name': self.customer_name,
            'customer_phone': self.customer_phone,
            'customer_address': self.customer_address,
            'quantity': self.quantity,
            'unit_price': self.unit_price,
            'total_price': self.total_price,
            'sale_date': self.sale_date.isoformat() if self.sale_date else None,
            'payment_method': self.payment_method,
            'status': self.status,
            'notes': self.notes,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }